var express = require('express')
var router = express.Router()
var request = require('request')
var path = require('path')
var removeMode = 1
var local = 0
var remoteHost = 'http://172.16.26.164:8080'

var muilter = require('./multerUtil')
// multer有single()中的名称必须是表单上传字段的name名称。
var upload = muilter.single('file')

if (removeMode) {
  router.all('/service/:app/imp/ds/upload', upload, function (req, res) {
    var r = request.post(remoteHost + '/service/app/imp/ds/upload', (err, resp, body) => {
      err && console.log(err)
      res.send(body)
    })
    var form = r.form()
    if (req.file) {
      form.append('file', fs.createReadStream(process.cwd() + '/' + req.file.path))
    }
  })

  router.all('/service/:app/imp/data/upload/:id', upload, function (req, res) {
    var r = request.post(remoteHost + req.path, (err, resp, body) => {
      err && console.log(err)
      res.send(body)
    })
    var form = r.form()
    if (req.file) {
      form.append('file', fs.createReadStream(process.cwd() + '/' + req.file.path))
    }
  })

  router.all('/service/:app/*', upload, function (req, res) {
    var host = remoteHost
    var data = req.body
    var reqPath = req.path
    var type = req.get('Content-Type')
    var otps = {
      method: req.method,
      url: host + req.path,
      query: req.query,
      headers: {
        'Content-Type': req.get('Content-Type'),
        'content-length': req.get('Content-length')
      }
    }
    // otps.headers = req.headers
    if (data) {
      if (type) {
        if (type.indexOf('form') >= 0) {
          otps.formData = JSON.parse(JSON.stringify(data))
        } else if (type.indexOf('json') >= 0) {
          otps.body = data
          otps.json = true
        }
      } else {
        otps.body = data
        otps.json = true
      }
    }

    if (req.query) {
      var f = ''
      for (let i in req.query) {
        f += i + '=' + req.query[i] + '&'
      }
      if (f !== '') {
        f = f.slice(0, -1)
        otps.url += '?' + f
      }
    }
    /*
    if (req.file) {
      otps.attachments = [
        fs.createReadStream(req.file.path)
      ]
    }
    */
    if (otps.formData && req.file) {
      otps.formData[req.file.fieldname] = fs.createReadStream(req.file.path)
    }
    if (otps.formData) {
      otps = {
        formData: otps.formData,
        url: otps.url,
        headers: {
          'Content-Type': req.get('Content-Type')
        // 'Content-length': req.get('Content-length')
        }
      }
    }
    var reqify = request(otps, function (error, response, body) {
      if (error) {
        console.error('TRANSMIT ERROR:' + error)
      }
      console.log('TRANSMIT DONE:' + req.path)
      res.send(body)
    })
    reqify
  // writeFile(reqify, 'Reuqeset.' + reqPath)
  })
}

function writeFile (text, path) {
  if (typeof text === 'object') text = JSON.stringify(text, null, '\t')
  path = process.cwd() + '/temp/' + path.replace(/\//g, '.') + '.json'
  fs.writeFile(path, text, (err) => {
  })
}

router.all('/menu', function (req, res) {
  setTimeout(() => {
    res.send([1, 2, 3, 4])
  }, 3000)
})

/**预设json数据文件读取逻辑 
 * 通过表示路由路径 . 表示路由中的 / , # 表示自定义变量
 * 从router-data开始的路径表示路由的前缀
 * TODO 设置默认路由动态提取json文件，根据路由参数生成文件路径并进行读取
 */

var fs = require('fs')
var dataList = []
var routesList = []
var dataFile = 'server/routes-data'
walkFile(dataFile)
for (let i in dataList) {
  let fl = dataList[i]
  let match = fl.match(/\/[^\/]+$/)
  if (match) {
    let name = match[0]
    let folder = fl.replace(dataFile, '').split('/')
    folder = folder.splice(0, folder.length - 1)
    let nameArr = name.split('.').slice(0, -1)
    let namePath = '/service/:app'
    let varCount = 0
    if (folder && folder.length) {
      namePath += folder.join('/')
    }
    for (let s in nameArr) {
      if (s > 0) namePath += '/'
      if (nameArr[s] === '#') {
        namePath += ':code_' + varCount++
      } else {
        namePath += nameArr[s]
      }
    }
    routesList.push({
      route: namePath,
      path: fl
    })
  }
}
// 生成路由函数
for (let i in routesList) {
  let route = routesList[i]
  router.all(route.route, function (req, res) {
    res.send(readJson(route.path))
  })
}

function readJson (filepath) {
  var str = fs.readFileSync(filepath).toString()

  // 去除注释
  str = str.replace(/\:\/\//g, '\:\\/\\/')
  str = str.replace(/\/\/[\s\S]*?\n/g, '')
  str = str.replace(/\/\/[\s\S]*?$/g, '')
  var res = false
  try {
    res = JSON.parse(str)
  } catch (ex1) {
    console.log(`json文件'${filepath}'解析错误`, ex1)
  }
  return res
}

function walkFile (ff) {
  let files = fs.readdirSync(ff)
  for (let fn in files) {
    let fname = ff + '/' + files[fn]
    let stat = fs.lstatSync(fname)
    if (stat.isDirectory() === true) {
      walkFile(fname)
    } else if (files[fn].match(/.(json)$/)) {
      dataList.push(fname)
    }
  }
}

module.exports = router
